/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove.impl;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.el.ELContext;
import javax.el.ELException;
import javax.el.ELResolver;
import javax.el.ExpressionFactory;
import javax.el.FunctionMapper;
import javax.el.ValueExpression;
import javax.el.VariableMapper;

import org.skatiger.jrove.Jrove;
import org.skatiger.jrove.JroveContext;
import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.TemplateClient;
import org.skatiger.jrove.TemplateContext;
import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.el.VariableMapperImpl;
import org.skatiger.jrove.util.AssertUtil;

final class DefaultJroveContext extends JroveContext implements TemplateContext {

    private final static class TemplateManager implements TemplateClient {
        private final DefaultJrove owner;

        private final TemplateClient target;

        private final boolean root;

        private final Set<String> names = new HashSet<String>();

        public TemplateManager(DefaultJrove owner, TemplateClient target,
                boolean root) {
            this.owner = owner;
            this.target = target;
            this.root = root;
        }

        public boolean apply(JroveContext ctx, UIComponent parent, String name)
                throws IOException, JroveException, ELException {
            String testName = (name != null) ? name : "jrove._NULL_DEF_";
            if (this.names.contains(testName)) {
                return false;
            } else {
                this.names.add(testName);
                boolean found = false;
                found = this.target.apply(new DefaultJroveContext(
                        (DefaultJroveContext) ctx, this.owner), parent, name);
                this.names.remove(testName);
                return found;
            }
        }

        @Override
        public boolean equals(Object o) {
            return this.owner == o || this.target == o;
        }

        @SuppressWarnings("unused")
        public boolean isRoot() {
            return this.root;
        }
    }

    private final ELContext _elctx;
    private final DefaultJrove _jrove;
    private final List<Jrove> _jroveHierarchy;
    private final ViewContext _viewContext;
    private final ExpressionFactory _expressionFactory;

    private VariableMapper _varMapper;

    private FunctionMapper _fnMapper;
    private final Map<String, Integer> ids;
    private final Map<Integer, Integer> prefixes;

    private String prefix;

    private final StringBuilder uniqueIdBuilder = new StringBuilder(30);

    private final List<TemplateClient> clients;

    public DefaultJroveContext(DefaultJroveContext ctx, DefaultJrove jrove) {
        this._elctx = ctx._elctx;
        this._expressionFactory = ctx._expressionFactory;
        this._viewContext = ctx._viewContext;
        this.clients = ctx.clients;
        this._fnMapper = ctx._fnMapper;
        this.ids = ctx.ids;
        this.prefixes = ctx.prefixes;
        this._varMapper = ctx._varMapper;
        this._jroveHierarchy = new ArrayList<Jrove>(
                ctx._jroveHierarchy.size() + 1);
        this._jroveHierarchy.addAll(ctx._jroveHierarchy);
        this._jroveHierarchy.add(jrove);
        this._jrove = jrove;
    }

    public DefaultJroveContext(ViewContext viewContext, DefaultJrove jrove) {
        this._elctx = viewContext.getELContext();
        this._viewContext = viewContext;
        this.ids = new HashMap<String, Integer>();
        this.prefixes = new HashMap<Integer, Integer>();
        this.clients = new ArrayList<TemplateClient>(5);
        this._jroveHierarchy = new ArrayList<Jrove>(1);
        this._jroveHierarchy.add(jrove);
        this._jrove = jrove;
        this._varMapper = this._elctx.getVariableMapper();
        this._expressionFactory = viewContext.getExpressionFactory();
        if (this._varMapper == null) {
            this._varMapper = new VariableMapperImpl();
        }
        this._fnMapper = this._elctx.getFunctionMapper();
    }

    public void extendClient(final TemplateClient client) {
        this.clients.add(new TemplateManager(this._jrove, client, false));
    }

    @Override
    public String generateUniqueId(String base) {
        if (prefix == null) {
            StringBuilder builder = new StringBuilder(
                    _jroveHierarchy.size() * 30);
            for (int i = 0; i < _jroveHierarchy.size(); i++) {
                DefaultJrove facelet = (DefaultJrove) _jroveHierarchy.get(i);
                builder.append(facelet.getAlias());
            }
            Integer prefixInt = new Integer(builder.toString().hashCode());

            Integer cnt = (Integer) prefixes.get(prefixInt);
            if (cnt == null) {
                this.prefixes.put(prefixInt, new Integer(0));
                prefix = prefixInt.toString();
            } else {
                int i = cnt.intValue() + 1;
                this.prefixes.put(prefixInt, new Integer(i));
                prefix = prefixInt + "_" + i;
            }
        }

        Integer cnt = (Integer) this.ids.get(base);
        if (cnt == null) {
            this.ids.put(base, new Integer(0));
            uniqueIdBuilder.delete(0, uniqueIdBuilder.length());
            uniqueIdBuilder.append(prefix);
            uniqueIdBuilder.append("_");
            uniqueIdBuilder.append(base);
            return uniqueIdBuilder.toString();
        } else {
            int i = cnt.intValue() + 1;
            this.ids.put(base, new Integer(i));
            uniqueIdBuilder.delete(0, uniqueIdBuilder.length());
            uniqueIdBuilder.append(prefix);
            uniqueIdBuilder.append("_");
            uniqueIdBuilder.append(base);
            uniqueIdBuilder.append("_");
            uniqueIdBuilder.append(i);
            return uniqueIdBuilder.toString();
        }
    }

    @Override
    public ELResolver getELResolver() {
        return this._elctx.getELResolver();
    }

    @Override
    public ExpressionFactory getExpressionFactory() {
        return this._expressionFactory;
    }

    @Override
    public FunctionMapper getFunctionMapper() {
        return this._fnMapper;
    }

    @Override
    public VariableMapper getVariableMapper() {
        return this._varMapper;
    }

    @Override
    public boolean includeDefinition(UIComponent parent, String name)
            throws IOException, JroveException, ELException {
        boolean found = false;
        TemplateManager client;

        for (int i = 0, size = this.clients.size(); i < size && !found; i++) {
            client = ((TemplateManager) this.clients.get(i));
            if (client.equals(this._jrove)) {
                continue;
            }
            found = client.apply(this, parent, name);
        }

        return found;
    }

    @Override
    public void includeJrove(UIComponent parent, String relativePath)
            throws IOException, JroveException, ELException {
        this._jrove.include(this, parent, relativePath);
    }

    @Override
    public void includeJrove(UIComponent parent, URL absolutePath)
            throws IOException, JroveException, ELException {
        this._jrove.include(this, parent, absolutePath);
    }

    @Override
    public boolean isPropertyResolved() {
        return this._elctx.isPropertyResolved();
    }

    public void popClient(TemplateClient client) {
        if (!this.clients.isEmpty()) {
            Iterator<TemplateClient> itr = this.clients.iterator();
            while (itr.hasNext()) {
                if (itr.next().equals(client)) {
                    itr.remove();
                    return;
                }
            }
        }
        throw new IllegalStateException(client + " not found");
    }

    public void pushClient(final TemplateClient client) {
        this.clients.add(0, new TemplateManager(this._jrove, client, true));
    }

    @Override
    public void putContext(Class key, Object contextObject) {
        this._elctx.putContext(key, contextObject);
    }

    @Override
    public void setFunctionMapper(FunctionMapper fnMapper) {
        AssertUtil.notNull(_varMapper, "functionMapper cannot be null");
        this._fnMapper = fnMapper;
    }

    @Override
    public void setPropertyResolved(boolean resolved) {
        this._elctx.setPropertyResolved(resolved);
    }

    @Override
    public void setVariableMapper(VariableMapper varMapper) {
        AssertUtil.notNull(varMapper, "varMapper cannot be null");
        this._varMapper = varMapper;
    }

    @Override
    public void setAttribute(String name, Object value) {
        if (this._varMapper != null) {
            if (value == null) {
                this._varMapper.setVariable(name, null);
            } else {
                this._varMapper.setVariable(name, this.getExpressionFactory()
                        .createValueExpression(value, Object.class));
            }
        }
    }

    @Override
    public Object getAttribute(String name) {
        if (this._varMapper != null) {
            ValueExpression ve = this._varMapper.resolveVariable(name);
            if (ve != null) {
                return ve.getValue(this);
            }
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.skatiger.jrove.JroveContext#getViewContext()
     */
    @Override
    public ViewContext getViewContext() {
        return _viewContext;
    }

}
